package com.qzsoft.zhjd.machine.modules.machinereport.service.impl;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.qzsoft.jeemis.common.utils.ConvertDictUtils;
import com.qzsoft.jeemis.platform.security.user.UserDetail;
import com.qzsoft.system.modules.permission.dept.dao.SysDeptMapper;
import com.qzsoft.system.repository.sys.entity.SysDeptEntity;
import com.qzsoft.zhjd.common.components.BaseServiceComponent;
import com.qzsoft.zhjd.machine.modules.machinereport.dto.MachineReportUseRateDeptDto;
import com.qzsoft.zhjd.machine.modules.machinereport.dto.MachineReportUseRateDto;
import com.qzsoft.zhjd.machine.modules.machinereport.mapper.MachineReportUseRateMapper;
import com.qzsoft.zhjd.machine.modules.machinereport.service.MachineReportUseRateService;

/**
 * @ClassName MachineReportUseRateServiceImpl
 * @Description 机械设备使用率业务接口实现
 * @author linhuawei
 * @since 2021-11-09
 */
@Service
public class MachineReportUseRateServiceImpl implements MachineReportUseRateService {

    @Autowired
    private BaseServiceComponent baseServiceComponent;

    @Autowired
    private MachineReportUseRateMapper machineReportUseRateMapper;

    @Autowired
    private SysDeptMapper sysDeptDao;

    @Override
    public IPage<MachineReportUseRateDto> machine(Map<String, Object> params) {
        // 计算统计天数
        int days = countDays(params);

        // 执行查询
        IPage<MachineReportUseRateDto> page = baseServiceComponent.getPage(params, MachineReportUseRateDto.class);
        page = machineReportUseRateMapper.machine(page, params);
        page = ConvertDictUtils.formatDicDataPage(page);
        page.getRecords().forEach(item -> {
            if(null != item) {
                item.setDays(days);
                item.count();
            }
        });
        return page;
    }

    @Override
    public MachineReportUseRateDeptDto dept(Map<String, Object> params) {
        // 计算统计天数
        int days = countDays(params);

        // 判断是否有机构主键
        UserDetail user = baseServiceComponent.basegetLoginUser();
        String deptId = user.getDeptId();
        if (null != params.get("deptId")) {
            String temp = params.get("deptId").toString();
            if (temp.startsWith(deptId)) {
                deptId = temp;
            }
        }
        params.put("deptId", deptId);

        // 获取当前机构
        SysDeptEntity dept = sysDeptDao.getRealId(deptId);
        MachineReportUseRateDeptDto result = machineReportUseRateMapper.dept(params);
        if (null == result) {
            result = new MachineReportUseRateDeptDto();
            result.setWorkTime(0L);
            result.setIdleTime(0L);
            result.setOffTime(0L);
            result.setEffectiveTime(0L);
            result.setTaiban(BigDecimal.ZERO);
            result.setAmount(0);
            result.setRate(BigDecimal.ZERO);
        }
        result.setDeptId(dept.getId());
        result.setDeptPkid(dept.getPkid());
        result.setDeptName(dept.getName());
        result.setDays(days);
        result.count();

        // 获取下级机构
        QueryWrapper<SysDeptEntity> query = new QueryWrapper<>();
        query.eq("pid", deptId).orderByAsc("sort", "id");
        List<SysDeptEntity> deptList = sysDeptDao.selectList(query);
        List<MachineReportUseRateDeptDto> list = null;
        if (ObjectUtils.isNotEmpty(deptList)) {
            MachineReportUseRateDeptDto dto = null;
            list = new ArrayList<MachineReportUseRateDeptDto>();
            for (int i = 0, len = deptList.size(); i < len; i++) {
                dept = deptList.get(i);
                if ("4".equals(dept.getType())) {
                    continue;// 磅房类型不参与统计
                }
                params.put("deptId", dept.getId());
                dto = machineReportUseRateMapper.dept(params);
                if (null == dto) {
                    dto = new MachineReportUseRateDeptDto();
                    dto.setWorkTime(0L);
                    dto.setIdleTime(0L);
                    dto.setOffTime(0L);
                    dto.setEffectiveTime(0L);
                    dto.setTaiban(BigDecimal.ZERO);
                    dto.setAmount(0);
                    dto.setRate(BigDecimal.ZERO);
                }
                dto.setDeptId(dept.getId());
                dto.setDeptPkid(dept.getPkid());
                dto.setDeptName(dept.getName());
                dto.setList(null);
                dto.setDays(days);
                dto.count();
                list.add(dto);
            }
        }
        result.setList(list);

        // 返回结果
        return result;
    }

    /**
     * @Title countDays
     * @Description 计算统计天数
     * @param params 查询条件
     * @return 统计天数
     */
    private int countDays(Map<String, Object> params) {

        // 必须有结束时间，如果没有传递，默认当前日期
        Date endTime = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if (null != params.get("endTime")) {
            try {
                endTime = sdf.parse(params.get("endTime").toString());
            } catch (ParseException e) {
                endTime = null;
            }
        }
        if (null == endTime) {
            Calendar cal = Calendar.getInstance();
            cal.set(Calendar.MILLISECOND, 0);
            cal.set(Calendar.SECOND, 0);
            cal.set(Calendar.MINUTE, 0);
            cal.set(Calendar.HOUR_OF_DAY, 0);
            endTime = cal.getTime();
        }

        // 必须有结束时间，如果没有结束时间，默认一周前时间
        Date startTime = null;
        if (null != params.get("startTime")) {
            try {
                startTime = sdf.parse(params.get("startTime").toString());
            } catch (ParseException e) {
                startTime = null;
            }
        }
        if (null == startTime) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(endTime);
            cal.add(Calendar.DATE, -6);
            startTime = cal.getTime();
        }

        // 设置开始结束时间
        params.put("startTime", sdf.format(startTime));
        params.put("endTime", sdf.format(endTime));

        // 判断相差天数
        int days = (int) ((endTime.getTime() - startTime.getTime()) / (1000 * 3600 * 24));
        return days;
    }

}
